package cn.openea.perpartner.growth.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.openea.perpartner.growth.entity.GrowthConfig;
import cn.openea.perpartner.growth.service.IGrowthConfigService;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.openea.perpartner.common.core.utils.Arith;
import cn.openea.perpartner.common.core.utils.StringUtils;
import cn.openea.perpartner.growth.entity.GrowthUserGrade;
import cn.openea.perpartner.growth.mapper.GrowthUserGradeMapper;
import cn.openea.perpartner.growth.service.IGrowthUserGradeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * (GrowthUserGrade)表服务实现类
 *
 * @author makejava
 * @since 2022-08-09 11:13:29
 */
@Service("growthUserGradeService")
public class GrowthUserGradeServiceImpl extends ServiceImpl<GrowthUserGradeMapper, GrowthUserGrade> implements IGrowthUserGradeService {
    @Autowired
    private IGrowthConfigService configService;
    @Override
    public JSONObject selectUserGrade(String userId) {
        LambdaQueryWrapper<GrowthUserGrade>  wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GrowthUserGrade::getUserid,userId);
        GrowthUserGrade grade = baseMapper.selectOne(wrapper);
        JSONObject gradeJson = new JSONObject();
        if(StringUtils.isNull(grade)){
            gradeJson.put("currentGrowthValue","0");
            gradeJson.put("currentGrowthLevel","V1");
            gradeJson.put("nextGrowthLevel","V2");
            gradeJson.put("nextGrowthValue","500");
            gradeJson.put("userGrowthValue","0");
        }else {
            String score = grade.getScore();
            GrowthConfig currentGrade = configService.selectCurrentGrade(score);
            GrowthConfig nextGrade = configService.selectNextGrade(score);
            gradeJson.put("currentGrowthValue",currentGrade.getScore());
            gradeJson.put("currentGrowthLevel",currentGrade.getGrade());
            gradeJson.put("nextGrowthLevel",nextGrade.getGrade());
            gradeJson.put("nextGrowthValue",nextGrade.getScore());
            gradeJson.put("userGrowthValue",score);
        }
        return gradeJson;
    }

    @Override
    public boolean update(String userId, String score) {
        LambdaQueryWrapper<GrowthUserGrade>  wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(GrowthUserGrade::getUserid,userId);
        GrowthUserGrade grade = baseMapper.selectOne(wrapper);
        if(BeanUtil.isEmpty(grade)){
            grade = new GrowthUserGrade();
            grade.setScore("0");
        }
        String growth = grade.getScore();
        double newValue = Arith.add(Double.parseDouble(growth), Double.parseDouble(score));
        grade.setScore(String.valueOf((int) newValue));
        return saveOrUpdate(grade);
    }
}

